const cache = (key) => {
  key = `store-${key}`
  return {
    get: () => {
      const res = localStorage.getItem(key)
      if (!res) return {}
      try {
        return JSON.parse(res)
      } catch (e) {
        return {}
      }
    },
    set: (data) => localStorage.setItem(key, JSON.stringify(data)),
  }
}

const modulesKeys = ['user', 'config']
const mutationsKeys = ['SET_USER', 'SET_CONFIG']

export default (store) => {
  // 设置默认值
  const cacheState = {}
  modulesKeys.forEach((key) => {
    const cacheItem = cache(key).get()
    if (Object.keys(cacheItem).length) {
      cacheState[key] = cacheItem
    }
  })
  store.replaceState({ ...store.state, ...cacheState })

  // 监听store
  store.subscribe((mutation, state) => {
    const i = mutationsKeys.indexOf(mutation.type)
    if (i === -1) return
    const key = modulesKeys[i]
    if (!key) return
    // 防止同步卡死视图
    setTimeout(() => {
      cache(key).set(store.state[key] || {})
    })
  })
}
